﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using ApplicationLibrary;

namespace ApplicationManager
{
    public partial class registerForm : Form
    {
        public bool LoadFromBinary = false;

        public registerForm(string applicationName)
        {
            InitializeComponent();
            lblApplication.Text = applicationName;
        }

        protected override void OnLoad(EventArgs e)
        {
            txtMac.Text = SerialManager.ReadMacAddress();
            if (LoadFromBinary)
                LoadDataFromBinary();

            LoadDataFromMenu();
            base.OnLoad(e);
        }

        private void LoadDataFromBinary()
        {
            SerialManager.Load();
            DataGridView1.Rows.Clear();

            foreach (SerialModule sd in SerialManager.SerialData.Modules)
            {
                int row = DataGridView1.Rows.Add();
                DataGridView1.Rows[row].Cells["colenable"].Value = sd.Enable == bool.TrueString;
                SerialType sType = (SerialType)Enum.Parse(typeof(SerialType), sd.SerialType);
                DataGridView1.Rows[row].Cells["colLicenseType"].Value = sType;
                DataGridView1.Rows[row].Cells["colApplication"].Value = sd.Application;
                DataGridView1.Rows[row].Cells["colModuleName"].Value = sd.Module;
                DataGridView1.Rows[row].Cells["colSerial"].Value = sd.SerialNo;
                if (sType.HasFlag(SerialType.EXPIRATION_DATE))
                    DataGridView1.Rows[row].Cells["colExpiration"].Value = sd.Expiration;

                txtLicense.Text = SerialManager.SerialData.License;
                txtPenDrive.Text = SerialManager.SerialData.PenDrive;
            }
        }

        private void LoadDataFromMenu()
        {
            string applPath = Path.GetDirectoryName(Application.ExecutablePath);
            string appConfname = Path.Combine(applPath, "ApplicationModules.config");

            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(appConfname);

            XmlNodeList xModules = xDoc.SelectNodes("modules/module");

            //if (xDoc.SelectSingleNode("modules").Attributes["pendrive"] != null)
            //    txtPendrive.Text = xDoc.SelectSingleNode("modules").Attributes["pendrive"].Value;

            foreach (XmlNode xModule in xModules)
            {
                string moduleCode = xModule.Attributes["code"].Value;
                NameSpace nSpace = new NameSpace(xModule.Attributes["namespace"].Value);

                string moduleDir = Path.Combine(applPath, nSpace.Folder);
                string menuFile = Path.Combine(moduleDir, "menu.config");

                if (!File.Exists(menuFile))
                {
                    MessageBox.Show("Missing menu file");
                    return;
                }

                XmlDocument xDocMenu = new XmlDocument();
                xDocMenu.Load(menuFile);

                XmlNodeList xMod = xDocMenu.SelectNodes("menu/module");

                foreach (XmlNode xSignleMod in xMod)
                {
                    if (LoadFromBinary && ModuleExist(moduleCode, xSignleMod.Attributes["code"].Value.ToString()))
                        continue;

                    int row = DataGridView1.Rows.Add();
                    DataGridView1.Rows[row].Cells["colenable"].Value = xSignleMod.Attributes["enable"].Value == bool.TrueString;
                    SerialType sType = (SerialType)Enum.Parse(typeof(SerialType), xSignleMod.Attributes["serialtype"].Value);
                    DataGridView1.Rows[row].Cells["colLicenseType"].Value = sType;
                    DataGridView1.Rows[row].Cells["colApplication"].Value = moduleCode;
                    DataGridView1.Rows[row].Cells["colModuleName"].Value = xSignleMod.Attributes["code"].Value;
                    if (sType.HasFlag(SerialType.EXPIRATION_DATE))
                        DataGridView1.Rows[row].Cells["colExpiration"].Value = xSignleMod.Attributes["expirationdate"].Value;
                }
            }
        }

        private bool ModuleExist(string application, string module)
        {
            for (int t = 0; t < DataGridView1.RowCount; t++)
            {
                if (DataGridView1.Rows[t].Cells["colApplication"].Value.ToString() == application &&
                    DataGridView1.Rows[t].Cells["colModuleName"].Value.ToString() == module)
                    return true;
            }
            return false;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!CheckData())
                return;

            SaveSerial();
            SerialManager.Load();
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private bool CheckData()
        {
            for (int t = 0; t < DataGridView1.RowCount; t++)
            {
                if (DataGridView1.Rows[t].Cells["colenable"].Value.ToString() == bool.TrueString &&
                    DataGridView1.Rows[t].Cells["colSerial"].Value == null)
                {
                    MessageBox.Show(Properties.Resources.Msg_MissingSerialNumber, Properties.Resources.Msg_Attention,
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

                DateTime expiration = DateTime.Today;
                SerialType sType = (SerialType)DataGridView1.Rows[t].Cells["colLicenseType"].Value;
                string application = (string)DataGridView1.Rows[t].Cells["colApplication"].Value;
                string module = (string)DataGridView1.Rows[t].Cells["colModuleName"].Value;
                if (sType.HasFlag(SerialType.EXPIRATION_DATE))
                    expiration = (DateTime)DateTime.Parse(DataGridView1.Rows[t].Cells["colExpiration"].Value.ToString());

                string serial = (string)DataGridView1.Rows[t].Cells["colSerial"].Value;

                if (serial != SerialManager.CreateSerial(txtLicense.Text, txtMac.Text, application, module, sType, expiration, txtPenDrive.Text))
                {
                    string mess = string.Format(Properties.Resources.Msg_IncorrectSerialNumber, application, module);
                    MessageBox.Show(mess, Properties.Resources.Msg_Attention,
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            }
            this.Close();
            return true;
        }

        private void SaveSerial()
        {
            SerialManager.Clear();
            SerialManager.SerialData.License = txtLicense.Text;
            SerialManager.SerialData.PenDrive = txtPenDrive.Text;

            for (int t = 0; t < DataGridView1.Rows.Count; t++)
            {
                DateTime expiration = DateTime.Today;
                bool enable = (bool)DataGridView1.Rows[t].Cells["colEnable"].Value;
                SerialType sType = (SerialType)DataGridView1.Rows[t].Cells["colLicenseType"].Value;
                string application = (string)DataGridView1.Rows[t].Cells["colApplication"].Value;
                string module = (string)DataGridView1.Rows[t].Cells["colModuleName"].Value;
                if (sType.HasFlag(SerialType.EXPIRATION_DATE))
                    expiration = DateTime.Parse(DataGridView1.Rows[t].Cells["colExpiration"].Value.ToString());
                string serial = DataGridView1.Rows[t].Cells["colSerial"].Value.ToString();
                SerialManager.AddModule(application, enable, module, sType, expiration, serial);
            }
            SerialManager.Save();
        }

        private void btnFindPen_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtPenDrive.Text = USBSerialNumber.GetNameFromDriveLetter(fbd.SelectedPath);
            }
        }
    }
}